package com.app.common.validator;

import com.app.common.exception.AppException;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;

import java.util.Set;

/**
 * @author : [zhuhj]
 * @version : [v1.0.0]
 * @description : [描述说明该类的功能]
 * @createTime : 2025/8/15
 * @updateUser : [zhuhj]
 * @updateTime : 2025/8/15
 * @updateRemark : [描述说明本次修改内容]
 */
public class ValidatorUtils {
    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     * @param object        待校验对象
     * @param groups        待校验的组
     * @throws AppException  校验不通过，则报AppException异常
     */
    public static void validateEntity(Object object, Class<?>... groups)
            throws AppException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            StringBuilder msg = new StringBuilder();
            for (ConstraintViolation<Object> constraint : constraintViolations) {
                msg.append(constraint.getMessage()).append("<br>");
            }
            throw new AppException(msg.toString());
        }
    }

}

